package com.itqf.realm;

import com.itqf.entity.SysUsers;
import com.itqf.service.SysUsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2020/11/20
 * @Time: 上午11:38
 */
public class MyUsersRealm extends AuthorizingRealm {
     Logger log = LoggerFactory.getLogger(MyUsersRealm.class);
     @Resource
     private SysUsersService sysUsersService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        log.info("---->授权");
        //作业： 授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //如何得到当前登录的用户编号？？？？？
        //认证的时候存储了用户对象  this.principals = new SimplePrincipalCollection(principal, realmName);
        SysUsers sysUsers = (SysUsers) principals.getPrimaryPrincipal();
        //根据当前登录的用户编号，查询用户的角色列表（Sys_Role  sys_user_role  sys_users）
        List<String> roles = sysUsersService.findRolesByUId(sysUsers.getId());
        //根据当前登录的用户编号，查询用户的权限列表（）
        List<String> perms = sysUsersService.findPermsByUId(sysUsers.getId());
     //["sys:mene:add",""]
        //stores roles and permissions
        simpleAuthorizationInfo.addRoles(roles);//Collection<String> roles
        simpleAuthorizationInfo.addStringPermissions(perms);//  sys:users:query
        log.info("---->授权完毕-->"+simpleAuthorizationInfo);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //得到用户输入的用户名和密码
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());
        log.info("---->认证（登录）-->"+username+"----"+password);
        SysUsers sysUsers =  sysUsersService.login(username);
        if (sysUsers==null){//
            throw  new UnknownAccountException("用户名错误！！");
        }
        if (!sysUsers.getPassword().equals(password)){
            throw  new IncorrectCredentialsException("密码错误");
        }
        if (sysUsers.getStatus()!=1){
            throw  new LockedAccountException("账号被冻结，请联系管理员！");
        }
       //Object principal, Object credentials(密文), String realmName
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo
                (sysUsers,password,this.getName());

        return info;
    }
}
